package com.gzcstec.order.receiver;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.reflect.TypeToken;
import com.gzcstec.order.utils.JsonUtils;
import com.gzcstec.product.dataobject.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ProductInfoReceiver {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String PRODUCTINFO_STOCK_TEMPLATE = "productInfo_stock_%s";

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String message) {
        //message ==> list
        List<ProductInfoOutput> productInfoOutputList =
                JsonUtils.fromJson(message, new TypeToken<List<ProductInfoOutput>>() {});
        //存放进redis缓存里面
        for(ProductInfoOutput productInfoOutput : productInfoOutputList) {
            redisTemplate.opsForValue()
                    .set(String.format(PRODUCTINFO_STOCK_TEMPLATE , productInfoOutput.getProductId()) ,
                            String.valueOf(productInfoOutput.getProductStock()));
        }
        log.info("【商品消息】message={}" , productInfoOutputList);
    }
}
